<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/21 0021
 * Time: 14:26
 */

namespace Cohuna\Services;


use Cohuna\Models\CohunaMerchantPay;

/**
 * 商户支付方式
 * @package Cohuna\Services
 */
class CohunaMerchantPayService extends ServiceBase
{
    /**
     * 添加或更新指定商户的支付配置
     * @param $mch_id
     * @param array $pay_id_list
     * @return bool|\Phalcon\Mvc\Model\QueryInterface
     */
    public function updateMerchantPayList($mch_id,array $pay_id_list)
    {
        $merchant_pay_list = CohunaMerchantPay::findByMerchantId($mch_id);
        if(empty($merchant_pay_list) && empty($pay_id_list)){
            return true;
        }
        if(empty($merchant_pay_list)){
            $this->db->begin();
            foreach ($pay_id_list as $pay_id) {
                $merchant_pay= new CohunaMerchantPay();
                $merchant_pay->pay_id = $pay_id;
                $merchant_pay->merchant_id = $mch_id;
                if(!$merchant_pay->save()){
                    $this->db->rollback();
                    return false;
                }
            }
            return $this->db->commit();
        }elseif (empty($pay_id_list)){
            $phql = 'DELETE FROM Cohuna\Models\CohunaMerchantPay WHERE merchant_id=:merchant_id:';
            return $this->modelsManager->executeQuery($phql,array('merchant_id'=>$mch_id));
        }else{
            $merchant_pay_array = array();
            $this->db->begin();

            foreach ($merchant_pay_list as $merchant_pay){
                //如果已有的支付信息不存在
                if(!in_array($merchant_pay->pay_id,$pay_id_list)){
                    if(!$merchant_pay->delete()){
                        $this->db->rollback();
                        return false;
                    }
                }else{
                    $merchant_pay_array[] = $merchant_pay->pay_id;
                }
            }
            foreach ($pay_id_list as $pay_id){
                if(!in_array($pay_id,$merchant_pay_array)){
                    $merchant_pay= new CohunaMerchantPay();
                    $merchant_pay->pay_id = $pay_id;
                    $merchant_pay->merchant_id = $mch_id;
                    if(!$merchant_pay->save()){
                        $this->db->rollback();
                        return false;
                    }
                }
            }
            return $this->db->commit();
        }
    }

    public function getMerchantPayList($mch_id)
    {
        $phql = 'SELECT pay.* FROM Cohuna\Models\CohunaMerchantPay AS mpay LEFT JOIN Cohuna\Models\CohunaPay AS pay ON mpay.pay_id=pay.pay_id WHERE mpay.merchant_id = :merchant_id:';

        $rows  = $this->modelsManager->executeQuery($phql,array('merchant_id'=>$mch_id));

        return $rows;

    }
}